<template>
  <div class="departments">
    <el-card>
      <template #header>
        <div>
          组织架构
        </div>
      </template>
      <div class="tree">
        <TreeItem :item="topInfo"></TreeItem>
        <hr />
        <el-tree :data="list" :props="{ children: 'children' }">
          <template v-slot="{ data }">
            <TreeItem
              style="width:100%"
              :item="data"
              @getData="getData"
            ></TreeItem>
          </template>
        </el-tree>
      </div>
    </el-card>
    <!-- 弹窗组件 props传值-->
    <DialogItem
      :lintList="lintList"
      @getData="getData"
      ref="dialogItem"
    ></DialogItem>
  </div>
</template>

<script>
import TreeItem from './components/tree-item'
import { companyDepartment } from '@/api/departments.js'
import DialogItem from './components/dialogitem.vue'

export default {
  components: {
    TreeItem,
    DialogItem
  },
  data () {
    return {
      topInfo: {
        name: '',
        manager: '',
        isTop: true,
        // 确定当前点击项的id
        id: ''
      },
      list: [],
      // 原始组织架构数据
      lintList: []
    }
  },
  created () {
    this.getData()
  },
  methods: {
    async getData () {
      const res = await companyDepartment()
      this.topInfo.name = res.data.companyName
      this.lintList = res.data.depts //存储原始数据
      this.list = this.changeData(res.data.depts, '')
      console.log('组织架构图:', this.list)
    },
    changeData (arr, str = '') {
      return arr.filter(item => {
        if (item.pid === str) {
          item.children = this.changeData(arr, item.id)
          return true
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.departments {
  padding: 20px;
  .tree {
    width: 90%;
    margin: 0 auto;
  }
}
</style>
